#include "StdAfx.h"
#include <gl/GL.h>
#include "TrackerView.hxx"
#include "ChannelView.hxx"
#include "SettingView.hxx"
#include "ChannelModel.hxx"


ChannelView::ChannelView(TrackerView* view):BaseView( view )
{
	_channelIndex = -1;
	
	_textureId = 0;

	_initialized = false;
}


ChannelView::~ChannelView(void)
{
	if( _textureId > 0 )
		glDeleteTextures( 1, &_textureId );
}

void ChannelView::initialize()
{
	glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_MODULATE);
    glGenTextures(1, &_textureId);
	
	glBindTexture(GL_TEXTURE_2D, _textureId);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    //glTexImage2D(GL_TEXTURE_2D,0,nComponents,nWidth, nHeight, 0,
    //             format, GL_UNSIGNED_BYTE, pBytes);
	if( _model )
	{
		IplImage* image = _model->getImage();
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,image->width, image->height, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, image->imageData);

		_initialized = true;
	}
}

void ChannelView::invalidate()
{
	BaseView::invalidate();
}

void ChannelView::render()
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glOrtho( -1.0, 1.0, -1.0, 1.0, -20.0, 20.0 );

	glMatrixMode(GL_MODELVIEW);

	int width = getRectWidth();
	int height = getRectHeight();
	
	int rindex = ( _channelIndex + 1 ) / 2;
	int cindex = ( _channelIndex ) % 2;

	int startx = cindex * 0.5 * width;
	int starty = rindex * 0.5 * height;

	if( isMaximized() )
		glViewport( 0, 0, width, height );
	else
        glViewport( startx, starty, width / 2, height / 2);

	glLoadIdentity();

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	if (isVisible())
		drawRectangle();

}

void ChannelView::drawRectangle()
{
	if( !_initialized )
		initialize();

	glDisable(GL_LIGHTING);
	
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, _textureId );
	
	if( !isValid() )
		replaceTexture();

	glColor3f( 1.0, 1.0, 1.0 );
	
	glBegin(GL_QUADS); // Drawing Using Triangles  
   
  glTexCoord2f( 0.0, 1.0 );
  glVertex3f( -1.0, -1.0, 0.0f );

  glTexCoord2f( 1.0, 1.0 );
  glVertex3f( 1.0, -1.0, 0.0f );

  glTexCoord2f( 1.0, 0.0 );
  glVertex3f( 1.0, 1.0, 0.0f );

  glTexCoord2f( 0.0, 0.0 );
  glVertex3f( -1.0, 1.0, 0.0f );
	
 glEnd();
}

void ChannelView::replaceTexture()
{
	IplImage* image = _model->getImage();
	glTexSubImage2D(GL_TEXTURE_2D,0,0,0,image->width,image->height,GL_BGR_EXT, GL_UNSIGNED_BYTE, image->imageData);

	if( getParent()->isSettingViewVisible() )
	{
		if( _channelIndex == getParent()->getSettingView()->getChannelIndex() )
		{
			getParent()->getSettingView()->invalidate();
		}
	}

	setValid();
}

